package common

import (
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"
)

type ErrResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

type SuccessResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

const SuccessCode = 200

func (e *ErrResponse) Error() string {
	return e.Msg
}

func NewErrResponse(code int, msg string) *ErrResponse {
	return &ErrResponse{
		Code: code,
		Msg:  msg,
	}
}

func UnAuthorizedCallback(w http.ResponseWriter, r *http.Request, err error) {
	httpx.WriteJson(w, http.StatusUnauthorized, NewErrResponse(http.StatusUnauthorized, err.Error()))
}

func ErrHandler(err error) (int, any) {
	switch e := err.(type) {
	case *ErrResponse:
		return http.StatusInternalServerError, *e
	default:
		logx.Errorf("Unhandler error found: %w", err)
		return http.StatusInternalServerError, *NewErrResponse(http.StatusInternalServerError, "internal server error")
	}
}

func NewSuccessResponse(data any) *SuccessResponse {
	return &SuccessResponse{
		Code: SuccessCode,
		Msg:  "success",
		Data: data,
	}
}
